const pool = require("../config/db"); //引入数据库连接池
const articleService = require("../service/articleService"); //引入用户服务

exports.articleList = (req, res) => {
  let pageNum = parseInt(req.query.pageNum) || 1; // 默认为第一页
  let pageSize = parseInt(req.query.pageSize) || 10; // 默认每页10篇文章
  // 验证page和pageSize是否是有效的数字
  if (isNaN(pageNum) || isNaN(pageSize) || pageNum < 1 || pageSize < 1) {
    return res.json({
      code: 400,
      msg: "参数错误",
      data: null,
    });
  }
  let offset = (pageNum - 1) * pageSize; // 计算偏移量
  console.log(pageNum, pageSize, offset);
  let author = req.query.author;
  // console.log(author);

  // 获取文章列表
  pool.query(
    articleService.getArticleByAuthor,
    [author || null, pageSize, offset],
    (err, articles) => {
      if (err) {
        res.json({
          code: 500,
          msg: "查询失败",
          data: err,
        });
      } else {
        // console.log(articles);

        // 获取文章总数
        pool.query(
          articleService.getTotalArticles,
          [author || null],
          (err, totalResult) => {
            if (err) {
              res.json({
                code: 500,
                msg: "获取文章总数失败",
                data: err,
              });
            } else {
              let total = totalResult[0].total; // 获取总文章数
              res.json({
                code: 200,
                msg: "查询成功",
                data: {
                  list: articles,
                  current: pageNum,
                  pageSize: pageSize,
                  total: total,
                },
              });
            }
          }
        );
      }
    }
  );
};
